#include "Texture.h"

#include <stdio.h>

std::map<std::string,Image*> Texture::c_images;
std::map<std::string,int> Texture::c_refcount;

Texture::Texture(std::string path,float diffuse,float reflective,float spec):Material(Pixelf(1,1,1),diffuse,reflective,spec){
    printf("Tex %s\n",path.c_str());
    m_path = path;
    m_img = Texture::loadTexture(path);
    Texture::incRef(path);
}
Texture::~Texture(){
    Texture::decRef(m_path);
}

Image* Texture::loadTexture(std::string& path){
    std::map<std::string,Image*>::iterator it = c_images.find(path);
    if (it==c_images.end()){
        Image* img = new Image();
        if (!img->loadPNG(path.c_str())){
            fprintf(stderr,"Couldn't load texture %s\n",path.c_str());
        }
        c_images[path] = img;
    }
    return c_images[path];
}

void Texture::incRef(std::string& path){
    c_refcount[path]++;
}

void Texture::decRef(std::string& path){
    c_refcount[path]--;
    if (c_refcount[path]==0){
        delete c_images[path];
    }       
}

Pixelf Texture::getAt(Math::Vector UV) const{
    int x = UV.x*m_img->getSizeX();
    int y = UV.y*m_img->getSizeY();
    return *(m_img->getAt(x,y));
}
